import { Ref } from 'vue'
import { ScrollSmooth, scrollTo as scrollToPosition } from '..'

/** 滚动 */
export default function useScroll(scroller: Ref<HTMLElement | null>) {
  /** 滚动到位置 */
  function scrollTo(top = 0, left?: number | null, smooth: ScrollSmooth = 'auto') {
    const el = scroller.value
    if (!el) return

    scrollToPosition(el, left ?? (el.scrollWidth - el.clientWidth) / 2, top, smooth)
  }

  return {
    /** 滚动到位置 */
    scrollTo,

    /** 滚动到顶部 */
    scrollToTop(smooth: ScrollSmooth = 'auto') {
      scrollTo(0, null, smooth)
    },

    /** 滚动到底部 */
    scrollToBottom(smooth: ScrollSmooth = 'auto') {
      scrollTo(scroller.value?.scrollHeight, null, smooth)
    },

    /**
     *
     * 按比例滚动
     * @param {number} ratio 滚动比例
     * @param {boolean} [smooth=true] 是否平滑滚动
     * @param {boolean} [scrollHeight=true] 滚动比例是否整个滚动区域高度，不包含 clientHeight
     */
    scrollToRatio(ratio: number, smooth: ScrollSmooth = 'auto', scrollHeight = false) {
      const el = scroller.value

      if (!el) return

      const h = scrollHeight ? el.scrollHeight : el.scrollHeight - el.clientHeight

      scrollToPosition(el, undefined, ratio * h, smooth)
    }
  }
}
